import math
import random

from kivy.app import App
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.graphics import Color, Rectangle, Ellipse, Line, Triangle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget

# 游戏设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60

# 地狱主题颜色
DARK_RED = (139/255, 0, 0, 1)
FIRE_ORANGE = (1, 69/255, 0, 1)
HELL_RED = (220/255, 20/255, 60/255, 1)
DARK_ORANGE = (1, 140/255, 0, 1)
YELLOW = (1, 1, 0, 1)
DARK_GRAY = (64/255, 64/255, 64/255, 1)
WHITE = (1, 1, 1, 1)
BLACK = (0, 0, 0, 1)

class Particle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.vx = random.uniform(-2, 2)
        self.vy = random.uniform(-3, -1)
        self.life = 30
        self.max_life = 30
        
    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.vy += 0.1
        self.life -= 1

class Bird:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.velocity = 0
        self.gravity = 0.5
        self.jump_strength = -8
        self.size = 25
        self.wing_angle = 0
        self.particles = []
        
    def jump(self):
        self.velocity = self.jump_strength
        # 添加跳跃粒子效果
        for _ in range(5):
            self.particles.append(Particle(self.x, self.y + 10))
        
    def update(self):
        self.velocity += self.gravity
        self.y += self.velocity
        self.wing_angle += 0.3
        
        # 更新粒子
        for particle in self.particles[:]:
            particle.update()
            if particle.life <= 0:
                self.particles.remove(particle)
        
    def get_rect(self):
        return (self.x - self.size, self.y - self.size, self.size * 2, self.size * 2)

class Pipe:
    def __init__(self, x):
        self.x = x
        self.width = 60
        self.gap = 150
        self.top_height = random.randint(100, SCREEN_HEIGHT - self.gap - 100)
        self.bottom_y = self.top_height + self.gap
        self.speed = 3
        self.passed = False
        
    def update(self):
        self.x -= self.speed
        
    def get_top_rect(self):
        return (self.x, 0, self.width, self.top_height)
        
    def get_bottom_rect(self):
        return (self.x, self.bottom_y, self.width, SCREEN_HEIGHT - self.bottom_y)
        
    def is_off_screen(self):
        return self.x + self.width < 0

class GameWidget(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.game_state = "start"  # start, playing, game_over
        self.bird = Bird(100, SCREEN_HEIGHT // 2)
        self.pipes = []
        self.score = 0
        self.background_particles = []
        
        # 初始化背景粒子
        for _ in range(20):
            self.background_particles.append({
                'x': random.randint(0, SCREEN_WIDTH),
                'y': random.randint(0, SCREEN_HEIGHT),
                'size': random.randint(1, 3),
                'speed': random.uniform(0.5, 2)
            })
        
        # 绑定触摸事件
        self.bind(on_touch_down=self.on_touch_down)
        
        # 设置大小
        self.size = (SCREEN_WIDTH, SCREEN_HEIGHT)
        
        # 开始游戏循环
        Clock.schedule_interval(self.update, 1.0/FPS)
        
    def on_touch_down(self, instance, touch):
        if self.game_state == "start":
            self.game_state = "playing"
        elif self.game_state == "game_over":
            self.game_state = "start"
            self.reset_game()
        elif self.game_state == "playing":
            self.bird.jump()
        return True
    
    def reset_game(self):
        self.bird = Bird(100, SCREEN_HEIGHT // 2)
        self.pipes = []
        self.score = 0
        self.game_state = "start"
    
    def update(self, dt):
        # 更新背景粒子
        for particle in self.background_particles:
            particle['x'] -= particle['speed']
            if particle['x'] < -10:
                particle['x'] = SCREEN_WIDTH + 10
                particle['y'] = random.randint(0, SCREEN_HEIGHT)
        
        if self.game_state == "playing":
            self.bird.update()
            
            # 检查小鸟是否撞地或撞天花板
            if self.bird.y > SCREEN_HEIGHT or self.bird.y < 0:
                self.game_state = "game_over"
                
            # 生成新管道
            if len(self.pipes) == 0 or self.pipes[-1].x < SCREEN_WIDTH - 200:
                self.pipes.append(Pipe(SCREEN_WIDTH))
                
            # 更新管道
            for pipe in self.pipes[:]:
                pipe.update()
                
                # 检查碰撞
                if self.game_state == "playing":
                    bird_rect = self.bird.get_rect()
                    top_rect = pipe.get_top_rect()
                    bottom_rect = pipe.get_bottom_rect()
                    
                    if (self.check_collision(bird_rect, top_rect) or 
                        self.check_collision(bird_rect, bottom_rect)):
                        self.game_state = "game_over"
                        
                # 计分
                if not pipe.passed and pipe.x + pipe.width < self.bird.x:
                    pipe.passed = True
                    self.score += 1
                    
                # 移除屏幕外的管道
                if pipe.is_off_screen():
                    self.pipes.remove(pipe)
        
        # 重绘
        self.canvas.clear()
        self.draw()
    
    def check_collision(self, rect1, rect2):
        x1, y1, w1, h1 = rect1
        x2, y2, w2, h2 = rect2
        return not (x1 + w1 < x2 or x2 + w2 < x1 or y1 + h1 < y2 or y2 + h2 < y1)
    
    def draw_hell_background(self):
        with self.canvas:
            # 绘制地狱背景渐变
            for y in range(0, SCREEN_HEIGHT, 2):
                ratio = y / SCREEN_HEIGHT
                r = 139/255 + (0 - 139/255) * ratio
                g = 0 + (0 - 0) * ratio
                b = 0 + (0 - 0) * ratio
                Color(r, g, b, 1)
                Rectangle(pos=(0, y), size=(SCREEN_WIDTH, 2))
            
            # 绘制背景粒子（火焰效果）
            for particle in self.background_particles:
                Color(*FIRE_ORANGE)
                Ellipse(pos=(particle['x'], particle['y']), size=(particle['size']*2, particle['size']*2))
    
    def draw_bird(self):
        with self.canvas:
            center_x, center_y = self.bird.x, self.bird.y
            
            # 身体（椭圆形）
            Color(*DARK_RED)
            Ellipse(pos=(center_x - 15, center_y - 10), size=(30, 20))
            
            # 头部
            Color(*HELL_RED)
            Ellipse(pos=(center_x - 8, center_y - 20), size=(16, 16))
            
            # 眼睛（发光的红色）
            Color(*FIRE_ORANGE)
            Ellipse(pos=(center_x - 5, center_y - 15), size=(8, 8))
            Ellipse(pos=(center_x + 5, center_y - 15), size=(8, 8))
            Color(*WHITE)
            Ellipse(pos=(center_x - 3, center_y - 13), size=(4, 4))
            Ellipse(pos=(center_x + 7, center_y - 13), size=(4, 4))
            
            # 翅膀（动态摆动）
            wing_offset = int(5 * math.sin(self.bird.wing_angle))
            Color(*DARK_ORANGE)
            Triangle(points=[
                center_x - 10, center_y + wing_offset,
                center_x - 25, center_y + 5 + wing_offset,
                center_x - 15, center_y + 10 + wing_offset
            ])
            
            # 尾巴
            Color(*DARK_RED)
            Triangle(points=[
                center_x + 15, center_y,
                center_x + 25, center_y - 5,
                center_x + 20, center_y + 5
            ])
            
            # 小角
            Color(*DARK_GRAY)
            Triangle(points=[
                center_x - 2, center_y - 25,
                center_x - 5, center_y - 30,
                center_x + 2, center_y - 25
            ])
            
            # 绘制粒子效果
            for particle in self.bird.particles:
                alpha = particle.life / particle.max_life
                Color(1, alpha, 0, alpha)
                Ellipse(pos=(particle.x, particle.y), size=(4, 4))
    
    def draw_pipes(self):
        with self.canvas:
            for pipe in self.pipes:
                # 上熔岩柱
                Color(*DARK_RED)
                Rectangle(pos=(pipe.x, 0), size=(pipe.width, pipe.top_height))
                Color(*HELL_RED)
                Rectangle(pos=(pipe.x + 5, 0), size=(pipe.width - 10, pipe.top_height))
                
                # 下熔岩柱
                Color(*DARK_RED)
                Rectangle(pos=(pipe.x, pipe.bottom_y), size=(pipe.width, SCREEN_HEIGHT - pipe.bottom_y))
                Color(*HELL_RED)
                Rectangle(pos=(pipe.x + 5, pipe.bottom_y), size=(pipe.width - 10, SCREEN_HEIGHT - pipe.bottom_y))
                
                # 添加熔岩纹理
                Color(*FIRE_ORANGE)
                for i in range(0, pipe.top_height, 20):
                    Line(points=[pipe.x, i, pipe.x + pipe.width, i], width=2)
                for i in range(pipe.bottom_y, SCREEN_HEIGHT, 20):
                    Line(points=[pipe.x, i, pipe.x + pipe.width, i], width=2)
    
    def draw_start_screen(self):
        self.draw_hell_background()
        
        with self.canvas:
            # 标题
            Color(*FIRE_ORANGE)
            # 这里需要字体支持，暂时用简单图形代替
            Rectangle(pos=(SCREEN_WIDTH//2 - 100, SCREEN_HEIGHT//2 - 100), size=(200, 50))
            
            # 开始按钮
            Color(*DARK_RED)
            Rectangle(pos=(SCREEN_WIDTH//2 - 100, SCREEN_HEIGHT//2 - 20), size=(200, 50))
            Color(*HELL_RED)
            Rectangle(pos=(SCREEN_WIDTH//2 - 95, SCREEN_HEIGHT//2 - 15), size=(190, 40))
            
            # 绘制演示小鸟
            self.draw_bird()
    
    def draw(self):
        if self.game_state == "start":
            self.draw_start_screen()
        else:
            # 绘制地狱背景
            self.draw_hell_background()
            
            # 绘制管道
            self.draw_pipes()
            
            # 绘制小鸟
            if self.game_state == "playing":
                self.draw_bird()
            
            # 绘制分数
            with self.canvas:
                Color(*WHITE)
                # 这里需要字体支持，暂时用简单图形代替
                Rectangle(pos=(10, SCREEN_HEIGHT - 30), size=(100, 20))
            
            # 绘制游戏结束信息
            if self.game_state == "game_over":
                with self.canvas:
                    Color(*FIRE_ORANGE)
                    Rectangle(pos=(SCREEN_WIDTH//2 - 100, SCREEN_HEIGHT//2 - 50), size=(200, 50))
                    Color(*WHITE)
                    Rectangle(pos=(SCREEN_WIDTH//2 - 100, SCREEN_HEIGHT//2 + 20), size=(200, 30))

class HellFlappyBirdApp(App):
    def build(self):
        # 设置窗口大小
        Window.size = (SCREEN_WIDTH, SCREEN_HEIGHT)
        
        # 创建主布局
        layout = FloatLayout()
        
        # 添加游戏组件
        game_widget = GameWidget()
        layout.add_widget(game_widget)
        
        return layout

if __name__ == '__main__':
    HellFlappyBirdApp().run()
